package com.admin.education.controllers.api.v1;

import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessage;
import com.admin.education.common.response.ResponseMessageWithData;
import com.admin.education.common.response.Result;
import com.admin.education.config.AppSettings;
import com.admin.education.common.utils.MD5Util;
import com.admin.education.models.File;
import com.admin.education.services.Implements.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/v1/files")
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private AppSettings appSettings;

    /**
     * 获取文件片信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ResponseBody
    public ResponseEntity<Object> serveFile(@PathVariable String id) {

        File file = fileService.getFileById(id);

        if (file != null) {
            return ResponseEntity
                    .ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=\"" + file.getName() + "\"")
                    .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                    .header(HttpHeaders.CONTENT_LENGTH, file.getSize() + "")
                    .header("Connection", "close")
                    .body(file.getContent());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File was not fount");
        }

    }


    /**
     * 上传
     *
     * @param file
     * @return
     */
    @PostMapping("")
    public IResponseMessage handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException, NoSuchAlgorithmException {
        IResponseMessage responseMessage = null;

        File f = new File(file.getOriginalFilename(), file.getContentType(), file.getSize(), file.getBytes());
        f.setMd5(MD5Util.getMD5(file.getInputStream()));
        fileService.saveFile(f);

        responseMessage = new ResponseMessageWithData<String>(Result.Success, appSettings.getServerUrl() +"v1/files/"+ f.getId());

        responseMessage.setLink(appSettings.getServerUrl()+"v1/files/"+f.getId());
        return responseMessage;
    }

    /**
     * 删除文件
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    @ResponseBody
    public IResponseMessage deleteFile(@PathVariable String id) {
        fileService.removeFile(id);
        IResponseMessage responseMessage = new ResponseMessage(Result.Success);
        return responseMessage;
    }
}
